import React, { useState, useEffect, useRef } from "react";

function VoiceToText() {
  const [transcript, setTranscript] = useState(""); // 用于存储语音转文字的结果
  const [isRecording, setIsRecording] = useState(false); // 用于标记是否正在录音
  const recognitionRef = useRef(null); // 使用 useRef 来存储语音识别实例

  const startRecording = () => {
    if ("SpeechRecognition" in window || "webkitSpeechRecognition" in window) {
      const SpeechRecognition =
        window.SpeechRecognition || window.webkitSpeechRecognition;
      const recognition = new SpeechRecognition();
      recognition.lang = "zh-CN"; // 设置语言为中文
      recognition.interimResults = true; // 允许返回临时结果
      recognition.continuous = true; // 开启连续识别模式

      recognition.onstart = () => {
        setIsRecording(true); // 开始录音时标记为正在录音
      };

      recognition.onresult = (event) => {
        const currentTranscript = Array.from(event.results)
          .map((result) => result[0].transcript)
          .join(" "); // 获取所有结果并拼接
        setTranscript(currentTranscript); // 更新状态以显示结果
        // console.log(currentTranscript);
      };

      recognition.onend = () => {
        setIsRecording(false); // 停止录音时标记为未录音
      };

      recognition.onerror = (event) => {
        console.error("语音识别错误：", event.error);
        setIsRecording(false); // 如果发生错误，标记为未录音
      };

      recognitionRef.current = recognition; // 将语音识别实例存储到 useRef 中
      recognition.start(); // 开始语音识别
    } else {
      alert("语音识别功能不支持此浏览器！"); // 如果浏览器不支持语音识别，提示用户
    }
  };

  const stopRecording = () => {
    if (recognitionRef.current) {
      recognitionRef.current.stop(); // 停止语音识别
      setIsRecording(false); // 标记为未录音
    }
  };

  return (
    <div>
      <h1>语音转文字</h1>
      <p>语音转文字结果：{transcript}</p>
      <button onClick={startRecording} disabled={isRecording}>
        开始录音
      </button>
      <button onClick={stopRecording} disabled={!isRecording}>
        停止录音
      </button>
    </div>
  );
}

export default VoiceToText;
